<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://unpkg.com/vue/dist/vue.js"></script>
        <script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script>
        <script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script>
    </head>
    <body>
        <div id="watchapp">
            <p>
                ask a yes/no question:
                <input v-model="question">
            </p>
            <p>{{answer}}</p>
        </div>
        
    <script>
    var vm_watch=new Vue({
        el:"#watchapp",
        data:{
            question:'',
            answer:'等待问题输入...'
        },
        watch: {
            //如果question的值发生变化，就会自动执行function
            question:function (newQuestion) {  
                this.answer='输入中...';
                this.getAnswer();
            }
        },
        methods: {
            // _.debounce 是一个通过lodsh 心智操作频率的函数
            // 在此例子中，希望限制访问api的频率
            // ajax请求直到用户输入完成后才会发出
            // 参考: https://lodash.com/docs#debounce
            getAnswer:_.debounce(
                function () {
                    var vm=this;
                    if(this.question.indexOf('?')===-1){
                        vm.answer='问题通常要有一个？';
                    }
                    vm.answer='思考答案中...';
                    axios.get('https://yesno.wtf/api')
                    .then(function(response){
                        vm.answer=_.capitalize(response.data.answer);
                    })
                    .catch(function(error){
                        vm.answer='Error! 没访问到api'+error;
                    })
                },
                //下面是为用户停止输入等待的毫秒数
                500
            )
        }

    });    
    </script>
    </body>
</html>
